﻿using CarterWechatServer.BizLogic.Account;
using CarterWechatServer.BizModel.Account;
using Microsoft.Owin.Security.OAuth;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading.Tasks;

namespace CarterWechatServer.WebApi.AuthorizationProvider
{
    /// <summary>
    /// 授权服务
    /// </summary>
    public class OpenAuthorizationProvider:OAuthAuthorizationServerProvider
    {
        private AccountService _accountService;

        public OpenAuthorizationProvider()
        {
            _accountService = new AccountService();
        }


        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            //获取客户端传递过来的ClientId和ClientSecret
            string clientId, clientSecret;
            context.TryGetFormCredentials(out clientId, out clientSecret);

            //判断客户端
            string clientType = context.Parameters.Get("client_type");
            if (clientType=="wechatOpen")
            {
                //在微信小程序中，直接将ClientId(OpenId) 作为授权的依据
                if (clientSecret=="carter")
                {
                    context.Validated(clientId);
                }
                else
                {
                    context.SetError("invalid_client", "客户端校验失败");
                }
            }
            return Task.FromResult(0);
        }

        /// <summary>
        /// 生成Access_Token（客户端模式）
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            UserInfoOutput output = _accountService.UserInfo(context.ClientId);
            if (output!=null)
            {
                //创建身份凭证
                var identity = new ClaimsIdentity(new GenericIdentity(
                        context.ClientId, OAuthDefaults.AuthenticationType
                    ));

                identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, output.UserId.ToString()));
                identity.AddClaim(new Claim("openId", context.ClientId));
                //生成凭据
                context.Validated(identity);
            }
            else
            {
                context.SetError("invalid_user", "不合法的用户");
            }
         

            return Task.FromResult(0);
        }
    }
}